require.config({
  baseUrl: '../../',
  paths: {
    jquery: 'plugins/jQuery/jquery-2.2.3.min',
    flavr: 'plugins/flavr/flavr.min',
    select2: 'plugins/select2/select2.min',
    fileinput: 'plugins/fileupload/fileinput.min',
    zh: 'plugins/fileupload/zh',
    public: 'public/js/public.min'
  },
  shim: {
    flavr: {
      deps: ['jquery']
    },
    select2: {
      deps: ['jquery']
    },
    fileinput: {
      deps: ['jquery']
    },
    zh: {
      deps: ['fileinput']
    }
  }
});
require(['jquery', 'flavr', 'select2', 'fileinput', 'zh', 'public'], function ($) {
  $(function () {
    var importObj = {
      errBox: {
        main: $('#err-message'),
        clear: function () {
          this.main.empty();
        }
      },
      init: function () {
        this.initSelect();
        this.initFileInput();
        this.bindEvent();
      },
      initSelect: function () {
        var year = new Date().getFullYear(),
          str = '',
          select;
        for (var i = year; i >= 2017; i--) {
          select = i === year ? ' selected' : '';
          str += '<option value="' + i + '" '+ select +'>' + i + '</option>';
        }
        $('#year').html(str);
        $('#year, #month').select2({
          width: 1.6 * rem
        });
      },
      initFileInput: function () {
        $('#file').fileinput({
          language: 'zh',
          required: true,
          showPreview: false,
          showUpload: false
        });
      },
      bindEvent: function () {
        var _this = this;
        $('#upload').click(function () {
          _this.errBox.clear();
          var formData = new FormData($('#import')[0]);
          publicAjax(basePath + 'excel/import', 'post', formData, function (data) {
            if (data.msg === '数据错误') {
              flavrShowByTime(data.msg, null, 'error', false);
              var str = '',
                list = data.data.errorMessage;
              for (var i = 0; i < list.length; i++) {
                str += '<p>' + list[i] + '</p>';
              }
              _this.errBox.main.html(str);
            } else if (data.msg.indexOf('已存在') !== -1) {
              flavrShow(data.msg + '，是否覆盖？', null, 'info', false, function () {
                publicAjax(basePath + 'excel/save', 'post', {year: $('#year').val(), month: $('#month').val()}, function (res) {
                  flavrShowByTime(res.msg, null, 'info', false);
                });
              });
            } else {
              flavrShowByTime(data.msg, null, 'info', false);
            }
          }, false, {processData: false,contentType:false,cache: false});
        });

        /* 下载模板 */
        $('#download').on('click', function () {
          location.href = basePath + 'public/template/template20180529.xlsx';
        });
      }
    };
    importObj.init();
  });
});